package cn.zgwj.user.service.impl;

import cn.zgwj.basic.constant.BaseConstants;
import cn.zgwj.basic.exception.BusinessException;
import cn.zgwj.basic.service.impl.BaseServiceImpl;
import cn.zgwj.basic.util.AjaxResult;
import cn.zgwj.basic.util.HttpClientUtils;
import cn.zgwj.basic.util.MD5Utils;
import cn.zgwj.basic.util.StrUtils;
import cn.zgwj.user.domain.Logininfo;
import cn.zgwj.user.domain.User;
import cn.zgwj.user.domain.WxUser;
import cn.zgwj.user.dto.LoginDto;
import cn.zgwj.user.dto.UserDto;
import cn.zgwj.user.mapper.LogininfoMapper;
import cn.zgwj.user.mapper.UserMapper;
import cn.zgwj.user.mapper.WxUserMapper;
import cn.zgwj.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public Map<String, Object> accountLogin(LoginDto dto) {
        //1.校验
        if(dto.getType() == null){
            throw new BusinessException("type一定要!!!");
        }
        //2.根据用户名查询数据库 t_logininfo
        Logininfo logininfo = logininfoMapper.loadByUserName(dto);
        //2.1查询不到报错
        if(logininfo == null){
            throw new BusinessException("用户不存在!!");
        }
        //2.2 查询到了,判断密码是否一致 加密之后判断
        String salt = logininfo.getSalt();
        //使用盐值加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if(!logininfo.getPassword().equals(md5Pwd)){
            throw new BusinessException("密码错误!!");
        }
        //3.登录成功
        String token = UUID.randomUUID().toString();//一定要加toString();
        //3.1 存redis
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象需要序列化
                30,
                TimeUnit.MINUTES
        );
        //3.2 返回登录成功的必要信息
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //我们作为高级技师,应该需要考虑到,将一些敏感信息屏蔽掉
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        return map;
    }

    @Override
    public AjaxResult wechat(String code) {
        // 空校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空");
        }
        // 根据code从微信获取token + openId
        String tokenUrl = BaseConstants.GET_TOKEN_URL
                .replace("APPID", BaseConstants.APPID)
                .replace("SECRET", BaseConstants.SECRET)
                .replace("CODE", code);
        String tokenObjStr =  HttpClientUtils.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        // 根据openId 查询t_wxuser
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        if(wxUser != null && wxUser.getUser_id() != null){
            //说明曾今已经扫码了,直接免密登录
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            String token = UUID.randomUUID().toString();//一定要加toString();
            //3.1 存redis
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,//对象需要序列化
                    30,
                    TimeUnit.MINUTES
            );
            //3.2 返回登录成功的必要信息
            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            //我们作为高级技师,应该需要考虑到,将一些敏感信息屏蔽掉
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo", logininfo);
            return AjaxResult.me().setResultObj(map);
        }else{//说明是第一次来,需要调到绑定页面,进行微信绑定
            String binderParams = "?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
        }
    }

    @Override
    public Map<String, Object> binderWechat(Map<String, String> params) {
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        //参数校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数不能为空");
        }
        //验证码是否有效 和验证码是否正确
        //二:校验验证码
        // 1.验证码是否过期
        Object codeTmp = redisTemplate.opsForValue().get(BaseConstants.BUSINESS_BINDER_PREFIX + phone);
        if (codeTmp == null) {
            throw new BusinessException("验证码已失效,请重新获取!");
        }
        // 2.验证码是否正确
        String code = ((String)codeTmp).split(":")[0];
        if(!verifyCode.equalsIgnoreCase(code)){//比对验证码不要区分大小写
            throw new BusinessException("验证码错误!!!");
        }

        //查询手机号是否被注册过 t_user
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if(user != null){
            //查询出已经存在的用户做微信绑定
            logininfo = logininfoMapper.loadById(user.getLogininfo_id());
        }else{
            //要直接生成新的
            user = initUser(phone);
            logininfo = user2Logininfo(user);
            // 1.保存logininfo
            logininfoMapper.save(logininfo);//返回自增id
            // 2.保存 user
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }
        // 调用微信，查询用户微信基本信息
        String getWxUserURL = BaseConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpClientUtils.httpGet(getWxUserURL);
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        wxUser.setUser_id(user.getId());//绑定用户
        wxUserMapper.save(wxUser);
        //直接免密登录
        String token = UUID.randomUUID().toString();//一定要加toString();
        //3.1 存redis
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象需要序列化
                30,
                TimeUnit.MINUTES
        );
        //3.2 返回登录成功的必要信息
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //我们作为高级技师,应该需要考虑到,将一些敏感信息屏蔽掉
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        return map;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //使用盐值加密
        String md5Pwd = MD5Utils.encrypByMd5("1" + salt);
        //应该发个短信告诉客人，您的初始密码是，请及时修改
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 同名原则拷贝
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
